﻿(function () {
    'use strict';
    Debug.enableFirstChanceException(true);

    WinJS.Application.onmainwindowactivated = function (e) {
        if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            CanvasTool.init({
                canvas: document.getElementById("canvas"),
                color: "black",
                size: document.getElementById("brushSize").value
            });

            document.getElementById("brushSize").onchange = brushSizeChanged;
            document.getElementById("brushDistance").onchange = brushDistanceChanged;
            document.getElementById("btnClear").onclick = btnClearClicked;
            document.getElementById("btnBrush").onclick = btnBrushClicked;

            colorInitialization();
        }
    }

    function colorInitialization() {
        WinJS.Utilities.query(".color").forEach(function (item) {
            item.style.background = item.getAttribute("data-color");
        });
        WinJS.Utilities.query(".color").listen("click", colorButtonClicked);
    }

    function brushSizeChanged() {
        CanvasTool.setBrushSize(document.getElementById("brushSize").value);
    }

    function brushDistanceChanged() {
        CanvasTool.setBrushDistance(document.getElementById("brushDistance").value);
    }

    function btnClearClicked() {
        CanvasTool.clear();
    }

    function btnBrushClicked() {
        
        var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
        openPicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.picturesLibrary;
        openPicker.fileTypeFilter.replaceAll([".png"]);
                
        openPicker.pickSingleFileAsync().then(function (file) {
            if (file) {
                var source = URL.createObjectURL(file, false);
                CanvasTool.setBrush(source);
            }
        });        
    }

    function colorButtonClicked(e) {
        WinJS.Utilities.query(".color").removeClass("selected");
        WinJS.Utilities.addClass(this, "selected");
        CanvasTool.setColor(this.getAttribute('data-color'));
    }

    WinJS.Application.start();
})();